<template>
  <div>
    <c-section title="任务基础信息">
      <c-list ref="form1" :model="formData" :rules="formRules" :column="3" label-width="145px">
        <c-list-item label="任务类型" prop="taskType" value="手工新增">
          <!-- <c-dict-select v-model="formData.taskType" dict-type-code="TASK_TYPE" placeholder="任务类型" /> -->
        </c-list-item>
        <c-list-item label="门店建设项目号" prop="constCode">
          <c-single-dialog
            ref="constCode"
            v-model="formData.constCode"
            :props="{label:'constCode',value:'constCode'}"
            :focus-query="true"
            :multiple="false"
            :config="{
              title:'门店建设项目号',
              width:'600px',
              interfacePath:'/slm-admin/api/v1/shopConstruct/allPage',
              method:'post',
              paramField:'constCode',
              filtersRaw:[],
              paramsRaw:{},
              setting:[
                {prop:'constCode',title:'门店建设项目号',width:120},
                {prop:'shopName',title:'门店'},
              ]
            }"
            @change="constCodeChangeHandle"
          />
        </c-list-item>
        <c-list-item label="门店建设范围" dict-type-code="DECORATION_RANGE" :value="shopDetail.decorationRange" />
        <c-list-item label="装修形式" dict-type-code="DECORATION_FORM" :value="shopDetail.decorationForm" />
        <c-list-item label="所属门店编码" :value="shopDetail.shopCode" />
        <c-list-item label="所属门店" :value="shopDetail.shopName" />
        <c-list-item label="所属客户编码" :value="shopDetail.clientCode" />
        <c-list-item label="所属客户" :value="shopDetail.clientName" />
        <c-list-item label="所属办事处" :value="shopDetail.officeName" />
      </c-list>

      <!-- 十月优化START -->
      <Area :design-detail="designDetail" />
      <!-- 十月优化END -->
      <c-list ref="form2" :model="formData" :rules="formRules" :column="3" label-width="145px">
        <c-list-item label="任务说明" :span="3" prop="taskDesc">
          <el-input v-model="formData.taskDesc" type="textarea" :autosize="{minRows: 3}" placeholder="任务说明" maxlength="1024" show-word-limit clearable />
        </c-list-item>
        <c-list-item label="是否重点市场" prop="isFocusMarket">
          <c-dict-select v-model="formData.isFocusMarket" dict-type-code="BOOLEANS" placeholder="是否重点市场" />
        </c-list-item>
        <c-list-item label="店面等级" prop="shopLevelCode">
          <c-dict-select v-model="formData.shopLevelCode" dict-type-code="SHOP_LEVEL_CODE" placeholder="店面等级" />
        </c-list-item>
        <c-list-item label="设计单位" prop="designUnitCode">
          <c-single-dialog
            ref="designUnitCode"
            v-model="formData.designUnitCode"
            :props="{label:'orgName',value:'orgCode'}"
            :label.sync="formData.designUnitName"
            :focus-query="true"
            :multiple="false"
            :config="{
              title:'设计单位',
              width:'600px',
              interfacePath:'/slm-admin/api/v1/user/orgTreeByType?type=9',
              method:'get',
              filtersRaw:[],
              paramsRaw:{},
              setting:[
                {prop:'orgCode',title:'编码'},
                {prop:'orgName',title:'名称'},
              ]
            }"
            @change="unitChange"
          />
        </c-list-item>
        <c-list-item label="设计范围" prop="designRange">
          <c-dict-checkbox-select v-model="formData.designRange" :includes="range" dict-type-code="DECORATION_RANGE" @change="rangeChange" />
        </c-list-item>
        <template v-if="formData.designRange.includes('DOOR')">
          <c-list-item key="dheadPicDesignType" label="门头图纸设计类型" prop="dheadPicDesignType">
            <c-dict-select v-model="formData.dheadPicDesignType" exclude="GH,BC" dict-type-code="PIC_TYPE" placeholder="门头图纸设计类型" @change="v=>changeHandle(v, 'DOOR')" />
          </c-list-item>
          <c-list-item key="dheadExpectCompleteTime" label="门头预计设计完成时间" prop="dheadExpectCompleteTime">
            <el-date-picker
              v-model="formData.dheadExpectCompleteTime"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
              clearable
            />
          </c-list-item>
        </template>
        <template v-if="formData.designRange.includes('STORES')">
          <c-list-item key="shopPicDesignType" label="卖场图纸设计类型" prop="shopPicDesignType">
            <c-dict-select v-model="formData.shopPicDesignType" exclude="PB" dict-type-code="PIC_TYPE" placeholder="卖场图纸设计类型" @change="v=>changeHandle(v, 'STORES')" />
          </c-list-item>
          <c-list-item key="marketExpectCompleteTime" label="卖场预计设计完成时间" prop="marketExpectCompleteTime">
            <el-date-picker
              v-model="formData.marketExpectCompleteTime"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
              clearable
            />
          </c-list-item>
        </template>
      </c-list>
    </c-section>
    <div class="btn-container">
      <c-button @click="cancelHandle">取消</c-button>
      <c-button type="primary" @click="submitHandle">提交</c-button>
    </div>
  </div>
</template>
<script>
import { getShopDesignInfo, postConfigTimeLimitPage, postAddShopDesignTask, getAllOrg9 } from '@/api/shopDesignTask'
import { SLMDict } from '@/api/dataDict'
import Area from './components/Area'
export default {
  name: 'ShopDesignTaskAddEdit',
  components: {
    Area
  },
  data() {
    const designRange = (r, v, c) => {
      if (v instanceof Array && v.length > 0) {
        c()
      } else {
        c(new Error('请选择设计范围'))
      }
    }
    return {
      shopDetail: {},
      designDetail: {},
      range: [],
      formData: {
        taskType: 'ARTIFICIAL',
        constCode: '',
        decorationRange: '',
        decorationForm: '',
        shopCode: '',
        shopName: '',
        clientCode: '',
        clientName: '',
        customerCode: '',
        customerName: '',
        officeCode: '',
        officeName: '',
        applySpecialZone: '',
        applyBizType: '',
        doorHeadPicArea: '',
        endProArea: '',
        publicSpaceArea: '',
        wholeHouseCustomizedArea: '',
        wholeCabinetArea: '',
        bathroomArea: '',
        sampleRoomArea: '',
        newBusinessAreaSummary: '',
        isSpecialDistrict: '',
        specialDistrictArea: '',
        softwareSumArea: '',
        suiteSumArea: '',
        taskDesc: '',
        picUrgentLevel: '',
        isKaMarket: '',
        isFocusMarket: '',
        shopLevelCode: '',
        haveRedesign: '',
        redesignReason: '',
        designUnitCode: '',
        designUnitName: '',
        marketExpectCompleteTime: '',
        dheadExpectCompleteTime: '',
        designRange: [],
        dheadPicDesignType: '',
        shopPicDesignType: '',

        //
        // dataSource: '',	// 任务来源
        newBusinessArea: '',	// 新业务面积汇总
        shopTotalArea: '',	// 卖场总面积
        otherCode: '' // 外部组织编码
      },
      formRules: {
        taskType: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
        constCode: [{ required: true, message: '请选择门店建设项目号', trigger: 'change' }],
        taskDesc: [{ required: true, message: '请选择任务说明', trigger: 'change' }],
        picUrgentLevel: [{ required: true, message: '请选择紧急程度', trigger: 'change' }],
        isKaMarket: [{ required: true, message: '请选择是否ka市场', trigger: 'change' }],
        isFocusMarket: [{ required: true, message: '请选择是否重点市场', trigger: 'change' }],
        shopLevelCode: [{ required: true, message: '请选择门店等级', trigger: 'change' }],
        haveRedesign: [{ required: true, message: '请选择是否包含重复设计', trigger: 'change' }],
        redesignReason: [{ required: true, message: '请输入重复设计原因', trigger: 'change' }],
        designUnitCode: [{ required: true, message: '请选择设计单位', trigger: 'change' }],
        designRange: [{ required: true, validator: designRange, trigger: 'change' }],
        dheadPicDesignType: [{ required: true, message: '请选择门头图纸设计类型', trigger: 'change' }],
        dheadExpectCompleteTime: [{ required: true, message: '请选择门头预计设计完成时间', trigger: 'change' }],
        shopPicDesignType: [{ required: true, message: '请选择卖场设计类型', trigger: 'change' }],
        marketExpectCompleteTime: [{ required: true, message: '请选择卖场图纸设计类型', trigger: 'change' }]
      },
      PIC_TYPE: [],
      orgs9: []
    }
  },
  created() {
    this.getAllOrg9()
  },
  methods: {
    getAllOrg9() {
      return getAllOrg9().then(res => {
        this.orgs9 = res.data
      })
    },
    async getOtherCode(code) {
      if (this.orgs9.length === 0) {
        await this.getAllOrg9()
      }
      for (const org of this.orgs9) {
        if (org.orgCode === code) {
          return org.otherCode
        }
      }
      return ''
    },
    constCodeChangeHandle(v) {
      this.shopDetail = v || {}
      this.range = []
      const keys = `picUrgentLevel isKaMarket isFocusMarket shopTotalArea shopLevelCode decorationRange decorationForm shopCode shopName clientCode clientName officeCode officeName applySpecialZone applyBizType doorHeadPicArea endProArea wholeHouseCustomizedArea wholeCabinetArea bathroomArea sampleRoomArea newBusinessAreaSummary softwareSumArea suiteSumArea designUnitCode designUnitName otherCode customerCode customerName customerPhone publicSpaceArea`.split(' ')
      for (const key of keys) {
        let value = v[key]
        if (value === undefined) value = ''
        this.$set(this.formData, key, value)
      }
      this.getOtherCode().then(otherCode => {
        this.$set(this.formData, 'otherCode', otherCode)
      })
      if (v.constCode === undefined) return
      getShopDesignInfo(v.constCode).then(res => {
        this.designDetail = res.data
        for (const key of Object.keys(this.formData)) {
          const v = res.data[key]
          if (v === undefined) continue
          this.$set(this.formData, key, v)
        }
        const { isRedesign, haveRedesign } = res.data
        this.$set(this.formData, 'haveRedesign', isRedesign !== undefined && isRedesign !== '' ? isRedesign : haveRedesign !== undefined && haveRedesign !== '' ? haveRedesign : '0')
        this.range = res.data.decorationRange ? res.data.decorationRange.split(',') : []
      })
    },
    async changeHandle(v, type) {
      await this.getDataDict()
      let label = ''
      if (v !== undefined) {
        for (const item of this.PIC_TYPE) {
          if (item.dictCode === v) {
            label = item.dictName
          }
        }
      }
      const bizType = []
      let key
      if (type === 'DOOR') {
        key = 'dheadExpectCompleteTime'
        bizType.push('C')
      } else {
        key = 'marketExpectCompleteTime'
        const t = this.formData.applyBizType || ''
        if (t.includes('01') || t.includes('A') || t.includes('PRODUCT')) {
          bizType.push('A')
        }
        if (t.includes('02') || t.includes('03') || t.includes('04') || t.includes('B') || t.includes('CUSTOMIZED') || t.includes('CUPBOARD') || t.includes('BATHROOM') || t.includes('MODEL')) {
          bizType.push('B')
        }
      }
      postConfigTimeLimitPage(type, label, bizType.join(',')).then(res => {
        const data = res.data.records
        let area = this.formData.doorHeadPicArea || 0
        if (type !== 'DOOR') {
          area = (this.formData.softwareSumArea || 0) + (this.formData.suiteSumArea || 0)
        }
        let day = 0
        if (v === 'SG' || v === 'XG') {
          day = Math.max(0, ...data.filter(e => {
            return e.minArea <= area && e.maxArea >= area
          }).map(e => e.timeLimit))
        } else if (v === 'BC' || v === 'GH' || v === 'PB') {
          day = data.filter(e => {
            return e.minArea <= area && e.maxArea >= area
          }).map(e => e.timeLimit).reduce((pre, cur) => {
            return pre + cur
          }, 0)
        }
        const now = new Date()
        const time = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime() + day * 24 * 3600 * 1000
        this.$set(this.formData, key, this.$parseTime(time))
      })
    },
    getDataDict() {
      if (this.PIC_TYPE.length > 0) return Promise.resolve()
      SLMDict('PIC_TYPE').then(res => {
        this.PIC_TYPE = res.data
      })
    },
    rangeChange(v) {
      if (!v.includes('DOOR')) {
        this.$set(this.formData, 'dheadPicDesignType', '')
        this.$set(this.formData, 'dheadExpectCompleteTime', '')
      }
      if (!v.includes('STORES')) {
        this.$set(this.formData, 'shopPicDesignType', '')
        this.$set(this.formData, 'marketExpectCompleteTime', '')
      }
    },
    cancelHandle() {
      this.$store.dispatch('views/goFirst')
    },
    submitHandle() {
      const p = Promise.all([this.$refs.form1.validate(), this.$refs.form2.validate()])
      return p.then(() => {
        const data = { ...this.formData }
        data.newBusinessArea = this.formData.newBusinessAreaSummary
        data.shopTotalArea = (this.formData.softwareSumArea || 0) + (this.formData.suiteSumArea || 0)
        data.designRange = (data.designRange || []).join(',')
        return postAddShopDesignTask(data).then(res => {
          this.$message.success('提交成功！')
          this.$store.dispatch('views/goFirst')
        })
      })
    },
    unitChange(v) {
      this.$set(this.formData, 'otherCode', v.otherCode === undefined ? '' : v.otherCode)
    }
  }
}
</script>
